﻿using UnityEngine;
using System.Collections;

/// <summary>
/// smooth look at target.
/// </summary>
[AddComponentMenu("wsLibrary/Control/Look At Smooth")]
public class wsLookAtSmooth : MonoBehaviour
{
	/// <summary>
	/// target to look at.
	/// </summary>
	public Transform target;
	/// <summary>
	/// damping value.
	/// </summary>
	public float damping = 6.0f;
	/// <summary>
	/// smooth look at.
	/// </summary>
	public bool smooth = true;
	/// <summary>
	/// look at reverse.
	/// </summary>
	public bool reverse = false;

	void Awake()
	{
		if (rigidbody)
			rigidbody.freezeRotation = true;
	}

	void LateUpdate()
	{
		if (target != null)
		{
			if (smooth)
			{
				// Look at and dampen the rotation
				//var rotation = Quaternion.LookRotation(target.position - transform.position);

				Quaternion rotation = Quaternion.identity;

				if (reverse)
					rotation = Quaternion.LookRotation(transform.position - target.position);
				else
					rotation = Quaternion.LookRotation(target.position - transform.position);

				transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
			}
			else
			{
				// Just lookat
				transform.LookAt(target);
			}
		}
	}
}
